using System.Reflection;
using Unity.Collections;
using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(FixedString128Bytes))]
public class FixedStringInspector : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        UnityEngine.Object obj = property.serializedObject.targetObject;
        string[] fields = property.propertyPath.Split('.');
        bool dirty = SetRecursive(obj, fields, position, property);
        if (dirty)
            EditorUtility.SetDirty(property.serializedObject.targetObject);
    }

    public static bool SetRecursive(object value, string[] fields, Rect position, SerializedProperty property, int index=0)
    {
        string fieldName = fields[index];
        FieldInfo field = value.GetType().GetField(fieldName);
        object currentValue = field.GetValue(value);
        bool dirty = false;
        if (index < fields.Length - 1)
        {
            dirty = SetRecursive(currentValue, fields, position, property, index + 1);
        }
        else
        {
            FieldInfo f128 = value.GetType().GetField(fieldName);
            currentValue = f128.GetValue(value);
            FixedString128Bytes f = (FixedString128Bytes)currentValue;
            string s1 = f.ToString();
            string s2 = EditorGUI.TextField(position, property.displayName, s1);
            currentValue = new FixedString128Bytes(s2);
            f128.SetValue(value, currentValue);
            dirty = s1!=s2;
        }
        field.SetValue(value, currentValue);
        return dirty;
    }
}